package com.golf.comms.server;

import java.net.MalformedURLException;

import org.apache.log4j.Logger;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.transport.Connector;

import com.golf.comms.Channels;

/**
 *
 * 
 * @author gfloodgate
 */
public class Server
{
	
	/** The logger instance. */
	private static final Logger log = Logger.getLogger(Server.class);

	
	/** The locator instance that defines where the server will listen. */
	private final InvokerLocator locator;
	
	/** The connector instance that runs the server. */
	private Connector connector;
	
	
	/**
	 * Create a new server instance with the given location. 
	 * 
	 * @param locator The locator to use to listen on upon startup.
	 * @throws Exception If there is a problem creating the server connector.
	 */
	public Server(final InvokerLocator locator) throws Exception
	{
		this.locator = locator;
	}
	
	
	/**
	 * Attempt to start the server instance listening for invocations.
	 * 
	 * @throws Exception If there is a problem with the startup.
	 */
	public void startup() throws Exception
	{
		log.info("Server startup initiaded.");

		// Create the server connector, and set it's location.
		connector = new Connector();
		connector.setInvokerLocator(locator.getLocatorURI());
		connector.create();

		// Add the invocation handlers for this server, and start it.
		connector.addInvocationHandler(Channels.USER, new UserInvocationHandler());
		connector.addInvocationHandler(Channels.LOBBY, new LobbyInvocationHandler());
		connector.addInvocationHandler(Channels.LOBBY_CHAT, new LobbyChatInvocationHandler());
		connector.start();
		
		log.info("Server startup completed successfully.");
	}
	
	
	/**
	 * Shutdown the server, stop it listening.
	 */
	public void shutdown()
	{
		if (connector != null)
		{
			log.info("Server shutdown initiaded.");
			connector.stop();
			connector.destroy();
		}
		else
		{
			log.warn("Server not running.");
		}
		
		log.info("Server shutdown completed successfully.");
	}
	
	
	/**
	 * The command line entry point. 
	 * 
	 * @param args The command line arguments passed to the server.
	 */
	public static final void main(final String[] args)
	{
		try
		{
			// The locator that the server will listen on.
			final InvokerLocator locator = new InvokerLocator("socket://" + args[0] + ":8084");
		
			// Create the server instance, and start it.
			final Server server = new Server(locator);
			server.startup();
		}
		catch (MalformedURLException mue)
		{
			log.error("Invalid server startup locator - " + mue.getMessage(), mue);
		}
		catch (Exception e)
		{
			log.error("Unexpected exception during server lifecycle - " + e.getMessage(), e);
		}
	}
	
}
